package view;

import javax.swing.*;
import java.awt.*;
import model.User;
import dao.UserDAO;
import javax.swing.table.DefaultTableModel;
import java.util.List;

public class UserPanel extends JPanel {
    private JTable userTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    
    public UserPanel() {
        setLayout(new BorderLayout());
        
        // 搜索和工具面板
        JPanel toolPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        searchField = new JTextField(20);
        JButton searchBtn = new JButton("搜索");
        JButton addBtn = new JButton("添加用户");
        JButton editBtn = new JButton("编辑");
        JButton deleteBtn = new JButton("删除");
        JButton resetPwdBtn = new JButton("重置密码");
        
        toolPanel.add(new JLabel("用户名："));
        toolPanel.add(searchField);
        toolPanel.add(searchBtn);
        toolPanel.add(addBtn);
        toolPanel.add(editBtn);
        toolPanel.add(deleteBtn);
        toolPanel.add(resetPwdBtn);
        
        // 设置按钮样式
        styleButton(searchBtn);
        styleButton(addBtn);
        styleButton(editBtn);
        styleButton(deleteBtn);
        styleButton(resetPwdBtn);
        
        add(toolPanel, BorderLayout.NORTH);
        
        // 初始化表格
        initTable();
        
        // 添加事件监听
        searchBtn.addActionListener(e -> searchUsers());
        addBtn.addActionListener(e -> showAddUserDialog());
        editBtn.addActionListener(e -> editSelectedUser());
        deleteBtn.addActionListener(e -> deleteSelectedUser());
        resetPwdBtn.addActionListener(e -> resetSelectedUserPassword());
        
        // 初始加载数据
        refreshTable();
    }
    
    private void styleButton(JButton button) {
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setFocusPainted(false);
        button.setBackground(new Color(59, 89, 152));
        button.setForeground(Color.WHITE);
        button.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
    }
    
    private void initTable() {
        String[] columns = {"ID", "用户名", "角色", "创建时间"};
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        userTable = new JTable(tableModel);
        userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        userTable.setRowHeight(25);
        userTable.getTableHeader().setReorderingAllowed(false);
        
        // 设置列宽
        userTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        userTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        userTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        userTable.getColumnModel().getColumn(3).setPreferredWidth(200);
        
        // 设置表格字体
        Font font = new Font("微软雅黑", Font.PLAIN, 14);
        userTable.setFont(font);
        userTable.getTableHeader().setFont(font);
        
        add(new JScrollPane(userTable), BorderLayout.CENTER);
    }
    
    private void searchUsers() {
        String keyword = searchField.getText().trim();
        UserDAO dao = new UserDAO();
        List<User> users = dao.searchUsers(keyword);
        updateTableData(users);
    }
    
    public void refreshTable() {
        UserDAO dao = new UserDAO();
        List<User> users = dao.getAllUsers();
        updateTableData(users);
    }
    
    private void updateTableData(List<User> users) {
        tableModel.setRowCount(0);
        for (User user : users) {
            Object[] row = {
                user.getId(),
                user.getUsername(),
                user.getRole(),
                user.getCreateTime()
            };
            tableModel.addRow(row);
        }
    }
    
    private void showAddUserDialog() {
        AddUserDialog dialog = new AddUserDialog((JFrame) SwingUtilities.getWindowAncestor(this), this);
        dialog.setVisible(true);
    }
    
    private void editSelectedUser() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow >= 0) {
            int userId = (int) tableModel.getValueAt(selectedRow, 0);
            String username = (String) tableModel.getValueAt(selectedRow, 1);
            String role = (String) tableModel.getValueAt(selectedRow, 2);
            
            EditUserDialog dialog = new EditUserDialog(
                (JFrame) SwingUtilities.getWindowAncestor(this),
                this,
                new User(userId, username, "", role, null)
            );
            dialog.setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要编辑的用户！");
        }
    }
    
    private void deleteSelectedUser() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow >= 0) {
            String username = (String) tableModel.getValueAt(selectedRow, 1);
            if ("admin".equals(username)) {
                JOptionPane.showMessageDialog(this, "不能删除管理员账号！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要删除该用户吗？",
                "确认删除",
                JOptionPane.YES_NO_OPTION
            );
            
            if (confirm == JOptionPane.YES_OPTION) {
                int userId = (int) tableModel.getValueAt(selectedRow, 0);
                UserDAO dao = new UserDAO();
                if (dao.deleteUser(userId)) {
                    JOptionPane.showMessageDialog(this, "删除成功！");
                    refreshTable();
                } else {
                    JOptionPane.showMessageDialog(this, "删除失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要删除的用户！");
        }
    }
    
    private void resetSelectedUserPassword() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow >= 0) {
            int userId = (int) tableModel.getValueAt(selectedRow, 0);
            String username = (String) tableModel.getValueAt(selectedRow, 1);
            
            int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要重置该用户的密码吗？\n重置后的密码将为：123456",
                "确认重置密码",
                JOptionPane.YES_NO_OPTION
            );
            
            if (confirm == JOptionPane.YES_OPTION) {
                UserDAO dao = new UserDAO();
                if (dao.resetPassword(userId)) {
                    JOptionPane.showMessageDialog(this, "密码重置成功！\n新密码：123456");
                } else {
                    JOptionPane.showMessageDialog(this, "密码重置失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要重置密码的用户！");
        }
    }
} 